package com.clippick.database;

import com.clippick.common.GlobalValue;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteDatabase.CursorFactory;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;

public class FeedOrderDBAdapter {
	private static final String DATABASE_NAME = "ImgMgr.db";
	public static String DATABASE_TABLE_PRE = "ImgMgrTB_";
//	private static String DATABASE_TABLE = "";
	private static final int DATABASE_VERSION = 1;

	// database key
	public final static String KEY_DB_INDEX = "NO";
	public final static String KEY_DB_ORDER = "HISTORY_IMG_ORDER";
	public final static String KEY_DB_TEXT_PATH = "HISTORY_IMG_PATH";
	public final static String KEY_DB_IMAGE_URL = "HISTORY_IMG_URLS";

	// database array
	public final static String[] DB_ARRAY = { KEY_DB_INDEX, KEY_DB_ORDER,
			KEY_DB_TEXT_PATH, KEY_DB_IMAGE_URL };

	private String DATABASE_TABLE_CREATE;
	private String DATABASE_TABLE_DROP;

	private SQLiteDatabase mDb;
	private DatabaseHelper mDbHelper;
	private static Context mContext;

	/** 이미지+텍스트가 클립될 경우, Text, Image 등 알맞은 뷰를 생성하기 위해서 각 클립마다 위치를 이 곳에 저장한다. */
	public FeedOrderDBAdapter(Context context, String BasicTableName) {
		mContext = context;
		createTable(BasicTableName);
		mDbHelper = new DatabaseHelper(mContext, DATABASE_NAME, null,
				DATABASE_VERSION);
	}

	public void createNewImageOrderTable(String tableName) {
		mDb.execSQL(DATABASE_TABLE_CREATE);
	}

	public String checkTableExists(String tableName) {
		String result = "";
		Cursor c = mDb.rawQuery(
				"SELECT name FROM sqlite_master WHERE type='table' AND name='"
						+ tableName + "'", null);

		if (c.moveToFirst()) {
			result = c.getString(c.getColumnIndexOrThrow("name"));
		}

		return result;
	}

	/**
	 * // open local database public FeedOrderDBAdapter open() throws
	 * SQLException { mDb = mDbHelper.getWritableDatabase();
	 * mDbHelper.creteTable(mDb); return this; }
	 */

	public void open() throws Exception {
		mDb = mDbHelper.getWritableDatabase();
	}

	public boolean isOpenDBfile() {
		return mDb != null ? mDb.isOpen() : false;
	}

	public void close() throws Exception {
		mDb.close();
	}

	// insert data
	public long insertFeed(long idx, String order, String textOrPath,
			String imageUrl) throws Exception {
		Cursor c = fetchFeedByIndex(idx);
		if (c.getCount() != 0) {
			c.close();
			return -1;
		}
		c.close();

		ContentValues values = new ContentValues();
		values.put(KEY_DB_INDEX, String.valueOf(idx));
		values.put(KEY_DB_ORDER, String.valueOf(order));
		values.put(KEY_DB_TEXT_PATH, textOrPath);
		values.put(KEY_DB_IMAGE_URL, imageUrl);
		return mDb.insert(GlobalValue.getImageOrderDbTableName(mContext), null,
				values);
	}

	// fetch data
	public Cursor fetchFeedByIndex(long idx) throws Exception {
		Cursor mCursor = mDb.query(true,
				GlobalValue.getImageOrderDbTableName(mContext), DB_ARRAY,
				KEY_DB_INDEX + "=" + "'" + idx + "'", null, null, null, null,
				null);

		if (mCursor != null)
			mCursor.moveToFirst();
		return mCursor;
	}

	// fetch all data order by Desc
	public Cursor fetchFeedByIndexOrderDesc(long index) throws Exception {
		Cursor mCursor = mDb.query(true,
				GlobalValue.getImageOrderDbTableName(mContext), DB_ARRAY,
				KEY_DB_INDEX + "=" + "'" + index + "'", null, null, null,
				KEY_DB_ORDER + " asc", null);

		if (mCursor != null)
			mCursor.moveToFirst();
		return mCursor;
	}

	// delete data
	public boolean deleteFeedByIndex(long index) throws Exception {
		Cursor c = fetchFeedByIndex(index);
		if (c.getCount() == 0) {
			c.close();
			return false;
		}
		c.close();

		try {
			mDb.execSQL("DELETE FROM "
					+ GlobalValue.getImageOrderDbTableName(mContext)
					+ " WHERE " + KEY_DB_INDEX + "=" + "'" + index + "'");
			return true;
		} catch (Exception e) {
			return false;
		}
	}

	// 테이블 만들기
	public void createTable(String _DatabaseID) {

		// DATABASE_TABLE = DATABASE_TABLE_PRE + _DatabaseID;

		DATABASE_TABLE_CREATE = "CREATE TABLE IF NOT EXISTS "
				+ GlobalValue.getImageOrderDbTableName(mContext)
				+ "(id INTEGER PRIMARY KEY AUTOINCREMENT,"
				+ "NO  							TEXT NOT NULL,"
				+ "HISTORY_IMG_ORDER  			TEXT NOT NULL,"
				+ "HISTORY_IMG_PATH				TEXT NOT NULL,"
				+ "HISTORY_IMG_URLS				TEXT NOT NULL);";

		DATABASE_TABLE_DROP = "DROP TABLE IF EXISTS "
				+ GlobalValue.getImageOrderDbTableName(mContext);
	}

	// DB 생성
	private class DatabaseHelper extends SQLiteOpenHelper {

		public DatabaseHelper(Context context, String name,
				CursorFactory factory, int version) {

			super(context, GlobalValue.getImageOrderDbTableName(mContext),
					null, DATABASE_VERSION);
		}

		@Override
		public void onCreate(SQLiteDatabase _db) {
			_db.execSQL(DATABASE_TABLE_CREATE);
		}

		/**
		 * public void creteTable(SQLiteDatabase _db) { onCreate(_db); }
		 */

		@Override
		public void onUpgrade(SQLiteDatabase _db, int oldVersion, int newVersion) {
			Log.w("MY_TAG", "Upgrading DB from version" + oldVersion + " to"
					+ newVersion + ", which will destroy all old data");

			_db.execSQL(DATABASE_TABLE_DROP);
			onCreate(_db);
		}
	}
}
